<template>
  <el-dialog
    class="ba-operate-dialog"
    :close-on-click-modal="false"
    :model-value="baTable.form.operate ? true : false"
    @close="baTable.toggleForm"
  >
    <template #header>
      <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']">
        {{ baTable.form.operate !== "edit" ? "添加" : "编辑" }}
      </div>
    </template>
    <el-scrollbar
      v-loading="baTable.form.loading"
      class="ba-table-form-scrollbar"
    >
      <div
        class="ba-operate-form"
        :class="'ba-' + baTable.form.operate + '-form'"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
      >
        <el-form
          ref="formRef"
          @keyup.enter="baTable.onSubmit(formRef)"
          :model="baTable.form.items"
          label-position="right"
          :label-width="baTable.form.labelWidth + 'px'"
          :rules="rules"
          v-if="!baTable.form.loading"
        >
          <!-- <el-form-item label="工单编号" prop="workinforNumber">
              <el-input v-model="baTable.form.items!.workinforNumber" />
            </el-form-item> -->
          <!-- <el-form-item label="支付订单编号" prop="orderNumber">
              <el-input v-model="baTable.form.items!.orderNumber" disabled />
            </el-form-item> -->
          <!-- <el-form-item label="设备编号" prop="deviceCode">
            <el-input
              v-model="baTable.form.items!.deviceCode"
              @blur="getAddress"
            />
            <div class="block-help">设备编号可由售后维护人员填写</div>
          </el-form-item> -->
          <el-form-item label="设备编号" prop="deviceCode">
            <el-input v-model="baTable.form.items!.deviceCode" @blur="getEid" />
            <div class="block-help">设备编号可由售后维护人员填写</div>
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="baTable.form.items!.deviceName" />
          </el-form-item>
          <!-- <el-form-item label="设备地址" prop="deviceAddress">
            <el-input
              v-model="baTable.form.items!.deviceAddress"
              @blur="getAddr"
            />
            <div class="block-help">如不指定服务企业请输入详细地址</div>
          </el-form-item> -->
          <el-form-item label="服务企业" prop="deviceAddress">
            <el-input
              v-model="filterText"
              placeholder="输入关键字进行过滤"
              style="background: whitesmoke"
            />
            <el-scrollbar
              ref="verticalMenusRef"
              class="vertical-menus-scrollbar"
              style="border: 1px solid #dcdfe6; width: 100%"
            >
              <el-tree
                ref="treeRef2"
                class="filter-tree"
                :data="state.companyOptions"
                :props="{ label: 'name', value: 'addr' }"
                node-key="id"
                show-checkbox
                default-expand-all
                :default-checked-keys="
                  baTable.form.operate == 'edit'
                    ? [baTable.form.items.customerId]
                    : []
                "
                :filter-node-method="filterNode"
                @check="rightClick"
              />
            </el-scrollbar>
            <div class="block-help">{{ baTable.form.items!.coordinate }}</div>
          </el-form-item>
          <!-- <el-form-item label="经度" prop="longitude">
              <el-input v-model="baTable.form.items!.longitude" />
            </el-form-item>
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="baTable.form.items!.latitude" />
            </el-form-item> -->
          <!-- <el-form-item label="设备型号" prop="deviceModel">
              <el-select
                v-model="baTable.form.items!.deviceModel"
                placeholder="请选择设备型号"
                @change="changeDeviceModel"
              >
                <el-option
                  v-for="item in state.modelOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item> -->
          <!-- <el-form-item label="行业名称" prop="businessScope">
              <el-select
                v-model="baTable.form.items!.businessScope"
                placeholder="请选择服务行业"
                @change="changeBusinessScope"
              >
                <el-option
                  v-for="item in state.scopeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item> -->
          <el-form-item label="服务项目" prop="projectName">
            <el-select
              v-model="baTable.form.items!.projectName"
              placeholder="请选择服务项目"
              @change="changeProjectName"
            >
              <el-option
                v-for="item in state.projectOptions"
                :key="item.id"
                :label="item.name"
                :value="item"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="维护人员" prop="employeeName">
            <el-select
              v-model="baTable.form.items!.employeeName"
              placeholder="请选择维护人员"
              @change="changeEmployee"
            >
              <el-option
                v-for="item in state.employeeOptions"
                :key="item.id"
                :label="item.name"
                :value="item"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="项目金额" prop="projectAmount">
            <el-input v-model="baTable.form.items!.projectAmount" disabled />
            <div class="block-help">
              项目金额需获取设备型号、服务行业名称、服务项目
            </div>
          </el-form-item> -->
          <FormItem
            prop="status"
            label="状态"
            v-model="baTable.form.items!.status"
            type="radio"
            :data="{
              content: {
                '0': '待派工',
                '1': '待执行',
                '2': '服务中',
                '3': '已完成',
                '4': '已取消',
                '5': '已考核',
              },
              childrenAttr: { border: true },
            }"
          />
          <el-form-item label="故障描述" prop="remark'">
            <el-input
              :rows="2"
              type="textarea"
              v-model="baTable.form.items!.remark"
            />
          </el-form-item>
          <!-- <el-form-item label="服务商" prop="providerName">
              <el-select
                v-model="baTable.form.items!.providerName"
                placeholder="请选择服务商"
                @change="changeService"
              >
                <el-option
                  v-for="item in state.serviceOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item> -->

          <!-- <el-form-item label="客户名称" prop="customerName">
              <el-select
                v-model="baTable.form.items!.customerName"
                placeholder="请选择客户名称"
                @change="changeCustomer"
              >
                <el-option
                  v-for="item in state.companyOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客户电话" prop="customerPhone">
              <el-input
                v-model="baTable.form.items!.customerPhone"
                maxlength="11"
                disabled
              />
              <div class="block-help">请先选择客户名称</div>
            </el-form-item> -->
          <el-form-item label="维修开始门头照">
            <el-upload
              ref="uploadRefStart"
              v-model:file-list="fileListStart"
              :headers="headerConfig"
              list-type="picture-card"
              :limit="1"
              name="idPhoto"
              :on-change="changUploadStart"
              :on-remove="handleRemoveStart"
              :auto-upload="false"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
            <div class="imgBox" style="margin-left: 10px">
              <el-image
                style="width: 148px; height: 148px"
                :src="baTable.form.items!.picture"
                fit="fill"
                :preview-src-list="[ baTable.form.items!.picture]"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
          </el-form-item>
          <el-form-item label="维修完成图片">
            <el-upload
              ref="uploadRef"
              v-model:file-list="fileList"
              :headers="headerConfig"
              list-type="picture-card"
              :limit="1"
              name="idPhoto"
              :on-change="changUpload"
              :on-remove="handleRemove"
              :auto-upload="false"
            >
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
            <div class="imgBox" style="margin-left: 10px">
              <el-image
                style="width: 148px; height: 148px"
                :src="baTable.form.items!.finishPhoto"
                fit="fill"
                :preview-src-list="[ baTable.form.items!.finishPhoto]"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div
        v-if="state.postOrder"
        :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'"
      >
        <el-button @click="baTable.toggleForm('')">取消</el-button>
        <el-button
          v-blur
          :loading="baTable.form.submitLoading"
          @click="baTable.onSubmit(formRef)"
          type="primary"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, inject, onMounted, watch, computed } from "vue";
import type baTableClass from "@/utils/baTable";
import FormItem from "@/components/formItem/index.vue";
import { useUser } from "@/store/backend/SysM/user";
import { useRegion } from "@/store/backend/SysM/region";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useConfig } from "@/store/config"; //后台布局相关仓库
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useCarbon } from "@/store/backend/EquipM/activeCarbon";
//   import { useModel } from "@/store/backend/DeviceM/model";
import { tree } from "@/utils/common";
import { _upload } from "@/utils/axios";
import { getPointByAddress } from "vue-baidu-map-3x"; //baidu-map组件red
import { ElNotification } from "element-plus"; //处理导航信息
import type {
  ElForm,
  FormRules,
  ElTree,
  UploadFile,
  UploadFiles,
  FormInstance,
  UploadProps,
  UploadUserFile,
  UploadInstance,
} from "element-plus";

const user = useUser();
const config = useConfig();
const region = useRegion();
const dictionary = useDictionary();
const carbon = useCarbon();
//   const model = useModel();
//接受来自父组件的注入
const baTable = inject("baTable") as baTableClass;
const project = inject("project") as any;
const staff = inject("staff") as any;
const business = inject("business") as any;
const access = inject("access") as any;

const treeRef = ref<InstanceType<typeof ElTree>>();
const formRef = ref<InstanceType<typeof ElForm>>();
const treeRef2 = ref<InstanceType<typeof ElTree>>(); //所属企业
const uploadRef = ref<UploadInstance>();
const uploadRefStart = ref<UploadInstance>();

const headerConfig = {
  Authorization: JSON.parse(localStorage.getItem("adminInfo") as any)?.token,
};

//服务开始照片
const fileListStart = ref<UploadUserFile[]>([]);
const realUploadFileStart = ref<UploadUserFile[]>([]);

// 服务完成照片
const fileList = ref<UploadUserFile[]>([]);
const realUploadFile = ref<UploadUserFile[]>([]);

type Option = {
  id: number;
  label: string;
  children: Option[];
};

const filterText = ref(""); //所示企业筛选

const filterNode = (value: string, data: any) => {
  console.log(value, data);

  if (!value) return true;
  return data.name.includes(value);
};

const state: {
  deptOptions: Option[];
  postOptions: anyObj[];
  roleOptions: anyObj[];
  regionOptions: anyObj[];
  companyOptions: anyObj[];
  regionLoading: boolean;
  id: number;
  menuExpand: boolean;
  menuNodeAll: boolean;
  menuCheckStrictly: boolean;
  genderDict: anyObj;
  genderDictArr: anyObj[];
  modelOptions: anyObj[];
  scopeOptions: anyObj[];
  projectOptions: anyObj[];
  serviceOptions: anyObj[];
  employeeOptions: anyObj[];
  devicesOptions: anyObj[];
  model: any[];
  scope: any[];
  form: anyObj;
  postOrder: boolean;
} = reactive({
  deptOptions: [], //部门列表
  postOptions: [], //岗位列表
  roleOptions: [], //角色列表
  regionOptions: [], //区域列表
  companyOptions: [], //企业列表
  regionLoading: false, //区域列表展示前的过渡动画
  id: 0,
  menuExpand: false,
  menuNodeAll: false,
  menuCheckStrictly: false,
  genderDict: {}, //用户性别字典项
  genderDictArr: [], //用户性别字典项
  modelOptions: [], //设备类型列表
  scopeOptions: [], //服务行业类型列表
  projectOptions: [], //服务项目列表
  serviceOptions: [], //服务商列表
  employeeOptions: [], //售后人员列表
  devicesOptions: [],
  model: [],
  scope: [],
  form: {
    businessScope: "",
    itemsId: 0, //服务项目id
  },
  postOrder: true,
});

//移除门头照片
const handleRemoveStart: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  const { uid } = uploadFile;
  const selectFileListstart = fileListStart.value.filter((item) => {
    return item.uid != uid;
  });
  fileListStart.value = selectFileListstart;
};

//门头照片照片文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changUploadStart: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("文件限制", uploadFile, uploadFiles[0].raw);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.png|.jpg|.jpeg$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.png|.jpg|.jpeg",
    });
    const selectFileListstart = fileListStart.value.filter((item) => {
      return item.uid != uid;
    });
    fileListStart.value = selectFileListstart;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileListstart = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileListStart.value = selectFileListstart;
    return;
  }
  //将上传的设备图片信息存入列表
  fileListStart.value.push(uploadFile);
  realUploadFileStart.value = [];
  let formData = new FormData();
  formData.append("file", uploadFiles[0].raw as any); //添加文件对象
  formData.append("name", "pic");
  _upload("/common/upload", formData, "").then((res: any) => {
    console.log("将上传的门头图片信息存入列表", res);
    baTable.form.items!.picture = res.data.url;
  });
};

//移除服务完成照片
const handleRemove: UploadProps["onRemove"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log(uploadFile, uploadFiles);
  const { uid } = uploadFile;
  const selectFileList = fileList.value.filter((item) => {
    return item.uid != uid;
  });
  fileList.value = selectFileList;
};

//服务完成照片文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changUpload: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  console.log("文件限制", uploadFile, uploadFiles[0].raw);
  const { uid, name, size } = uploadFile;
  //   文件类型限制
  const fileTypeFlag = /^.png|.jpg|.jpeg$/.test(
    name.substring(name.lastIndexOf(".")).toLowerCase()
  );
  if (!fileTypeFlag) {
    ElNotification({
      type: "warning",
      message: "文件类型只能是.png|.jpg|.jpeg",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  //文件大小进行校验
  if ((size as number) > 1024 * 1024 * 5) {
    ElNotification({
      type: "warning",
      message: "文件大小不能超过5Mb",
    });
    const selectFileList = fileList.value.filter((item) => {
      return item.uid != uid;
    });
    fileList.value = selectFileList;
    return;
  }
  //将上传的设备图片信息存入列表
  fileList.value.push(uploadFile);
  realUploadFile.value = [];
  let formData = new FormData();
  formData.append("file", uploadFiles[0].raw as any); //添加文件对象
  formData.append("name", "pic");
  _upload("/common/upload", formData, "").then((res: any) => {
    console.log("将上传的设备图片信息存入列表", res);
    baTable.form.items!.finishPhoto = res.data.url;
    // baTable.form.items!.idPhoto =
    //   "http://47.103.39.74:8088" + res.data.fileName;
  });
};

const userCheck = (MouseEvent: any, object: any, Node: any, element: any) => {
  baTable.form.items!.companyid = MouseEvent.id;
};
// 树权限（展开/折叠）
const handleCheckedTreeExpand = (value: any, type: any) => {
  let treeList = region.originData; //原始区域数据
  for (let i = 0; i < treeList.length; i++) {
    treeRef.value!.store.nodesMap[treeList[i].areaId].expanded = value;
  }
};
// 树权限（全选/全不选）
const handleCheckedTreeNodeAll = (value: any, type: any) => {
  //原始区域数据
  treeRef.value!.setCheckedNodes(value ? (region.originData as any) : []);
};
// 树权限（父子联动）
const handleCheckedTreeConnect = (value: any, type: any) => {
  state.menuCheckStrictly = value ? true : false;
};

//选择设备编号
const rightClick = (MouseEvent: any, object: any, Node: any, element: any) => {
  // getAddr(); //获取企业坐标
  console.log("企业选择的数据", MouseEvent, object, Node, element);
  if (object.checkedKeys.length) {
    baTable.form.items!.deviceAddress = MouseEvent.addr; //地址
    baTable.form.items!.customerName = MouseEvent.name; //客户企业名称
    baTable.form.items!.customerId = MouseEvent.id; //客户id
    getAddr(); //获取经纬度
  } else {
    //清空经纬度与地址
    baTable.form.items!.deviceAddress = "";
    baTable.form.items!.coordinate = "";
  }
};

//地址转换为坐标
const getAddr = () => {
  getPointByAddress(
    {
      address: baTable.form.items!.deviceAddress,
    },
    ["wZcU7ugfOpZLuuRTAvNPn3Y36rpFxp1Q"]
  )
    .then((res) => {
      let { location, formatted_address } = res as any;
      console.log("坐标", location);
      baTable.form.items!.coordinate = JSON.stringify(location);
    })
    .catch((err: any) => {
      console.log(err);
      ElNotification({
        type: "warning",
        message: err + ",请检查并填写正确企业地址",
      });
      baTable.form.items!.deviceAddress = "";
      baTable.form.items!.coordinate = "";
    });
};

// 表单验证
const rules = reactive<FormRules>({
  deviceCode: [
    {
      required: true,
      message: "设备编号必填",
      trigger: "blur",
    },
  ],
  deviceAddress: [
    {
      required: true,
      message: "服务企业必选",
      trigger: "blur",
    },
  ],
  deviceName: [
    {
      required: true,
      message: "设备名称必填",
      trigger: "blur",
    },
  ],
  employeeName: [
    {
      required: true,
      message: "维护人员必选",
      trigger: "blur",
    },
  ],
  projectName: [
    {
      required: true,
      message: "服务项目必选",
      trigger: "blur",
    },
  ],
  // phone: [
  //   {
  //     required: true,
  //     message: "登录手机号不能为空",
  //     trigger: "blur",
  //   },
  //   {
  //     validator: function (rule, value, callback) {
  //       // const title = /^[\a-\z\A-\Z0-9\u4e00-\u9fe5]+$/;中英文
  //       const title = /^[\a-\z\A-\Z0-9]+$/;
  //       if (!title.test(value)) {
  //         callback(new Error("标题只能输入数字和英文"));
  //       } else {
  //         callback();
  //       }
  //     },
  //     trigger: "blur",
  //   },
  // ],
  phone: [
    {
      required: true,
      message: "联系方式",
      trigger: "blur",
    },
    {
      validator: function (rule, value, callback) {
        if (/^1[34578]\d{9}$/.test(value) == false) {
          callback(new Error("手机号格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
    // { type: "string", message: "长度不能超过30位", trigger: "blur", max: 30 },
  ],
  // email: [
  //   {
  //     required: true,
  //     message: "请输入邮箱",
  //     trigger: "blur",
  //   },
  //   {
  //     validator: function (rule, value, callback) {
  //       if (
  //         /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(value) ==
  //         false
  //       ) {
  //         callback(new Error("邮箱格式错误"));
  //       } else {
  //         callback();
  //       }
  //     },
  //     trigger: "blur",
  //   },
  // ],
});

//获取设备eid
const getEid = () => {
  if (baTable.form.items!.deviceCode) {
    carbon
      .getListByRegions({
        ecode: baTable.form.items!.deviceCode,
        regions: region.regionIds + "",
      })
      .then((res: any) => {
        console.log("获取设备eid判断是否激活", res);
        if (
          res.rows.length > 0 &&
          res.rows[0].state !== "2" &&
          res.rows[0].state !== "3"
        ) {
          state.postOrder = state.postOrder ? state.postOrder : true;
          baTable.form.items!.eid = res.rows[0].eid;
        } else {
          state.postOrder = false;
          alert("设备还未投入生产无法进行维护服务");
        }
      });
  }
};

const append = (data: any) => {
  console.log("data", data);
  baTable.form.items!.regionName = data.areaName;
};
const getCheckeds = () => {
  return treeRef.value
    ?.getCheckedKeys()
    .concat(treeRef.value!.getHalfCheckedKeys());
};

//获取区域列表
const getRegionListByRole = () => {
  region
    .getRegionByRole()
    .then((res: any) => {
      state.regionOptions = res;
      state.regionLoading = false;
    })
    .catch(() => {
      state.regionLoading = false;
    });
};
const getCompanyList = () => {
  const business = useBusiness();
  const { companyList } = business;
  if (companyList.length === 0) {
    business.getCompanyList().then((res: any) => {
      state.companyOptions = res.rows;
      console.log("state.companyOptions", state.companyOptions);
    });
  } else {
    state.companyOptions = companyList;
    console.log("state.companyOptions", state.companyOptions);
  }
};

//针对侧边栏菜单高度让滚动条自适应
const overviewMenusScrollbarHeight = computed(() => {
  // 加上了50px的头部距离
  let menuTopBarHeight = 50;
  if (config.layout.layoutMode == "Default") {
    //32为aside上下margin
    return "calc(100vh - " + (172 + menuTopBarHeight) + "px)";
  } else {
    return "calc(100vh - " + (140 + menuTopBarHeight) + "px)";
  }
});

//选择设备型号
// const changeDeviceModel = (e: any) => {
//   getPrice();
// };
// //选择客户
// const changeCustomer = (e: any) => {
//   console.log("选择客户", e);
//   baTable.form.items!.customerId = e.id;
//   baTable.form.items!.customerName = e.name;
//   baTable.form.items!.customerPhone = e.phone;
// };
// //选择服务行业
// const changeBusinessScope = (e: any) => {
//   console.log("选择服务行业", e);
//   baTable.form.items!.businessScope = e.name;
//   baTable.form.items!.scopeId = e.id;
//   getPrice();
// };
//选择项目名称
const changeProjectName = (e: any) => {
  console.log("选择服务项目", e);
  baTable.form.items!.projectName = e.name;
  baTable.form.items!.projectId = e.id; //项目id
  state.form.itemsId = e.id;
};

// //指定服务商
// const changeService = (e: any) => {
//   console.log("选择服务商被触发", e);
//   baTable.form.items!.providerName = e.name;
//   baTable.form.items!.providerId = e.id; //服务商id赋值
//   getEmployee(e.id);
// };

//获取售后人员
const getEmployee = () => {
  staff
    .getSingleAndListStaffAuto({ pageNum: 1, pageSize: 1000 })
    .then((res: any) => {
      console.log("售后人员", res);
      state.employeeOptions = tree(res.rows, "name", "name");
    });
};

//选择售后人员
const changeEmployee = (e: any) => {
  console.log("选择售后人员", e);
  baTable.form.items!.employeeName = e.name; //分配售后人员名称
  baTable.form.items!.employeeId = e.id; //分配售后人员id
  baTable.form.items!.status = "1";
};

//获取服务项目定价
// const getPrice = () => {
//   if (
//     baTable.form.items!.deviceModel &&
//     baTable.form.items!.businessScope &&
//     baTable.form.items!.projectId
//   ) {
//     price
//       .getPrice({
//         deviceModel: baTable.form.items!.deviceModel,
//         businessScopeName: baTable.form.items!.businessScope,
//         itemsId: baTable.form.items!.projectId,
//         price: "",
//         pageNum: 1,
//         pageSize: 10,
//       })
//       .then((res: any) => {
//         console.log("获取服务项目定价", res);
//         if (res.rows.length) {
//           baTable.form.items!.projectAmount = res.rows[0].price;
//         } else {
//           //为空
//           ElNotification({
//             type: "warning",
//             message: "该项目价格未定,请前往项目定价管理进行定价",
//           });
//           baTable.form.items!.projectAmount = "";
//         }
//       });
//   }
// };

//获取设备编号的设备地址
const getAddress = () => {
  access
    .getAccessList({ code: baTable.form.items!.deviceCode })
    .then((res: any) => {
      if (res.rows.length) {
        baTable.form.items!.deviceAddress = res.rows[0].addr;
        //判断有无服务商id
        if (!baTable.form.items!.providerId) {
          //获取经纬度
          getAddr();
        }
      }
    });
};

onMounted(() => {
  //获取设备类型列表
  // model.getList().then((res: any) => {
  //   console.log("设备类型列表", res);
  //   state.modelOptions = tree(res.rows, "type", "type");
  // });
  //获取服务项目列表
  project.getProjectList({}).then((res: any) => {
    console.log("服务项目", res);
    state.projectOptions = tree(res.rows, "serviceName", "serviceName");
  });
  //获取行业列表
  // scope.getScopeList().then((res: any) => {
  //   console.log("行业名称", res);
  //   state.scopeOptions = tree(res.rows, "name", "id");
  // });
  //获取服务商列表
  // service.getSingleServiceAuto({}).then((res: any) => {
  //   console.log("服务商", res);
  //   state.serviceOptions = tree(res.rows, "name", "name");
  // });
  //获取企业用户列表
  business.getCompanyList().then((res: any) => {
    console.log("企业用户列表", res);
    state.companyOptions = res.rows;
    // state.companyOptions = treeCustomer(res.rows, "name", "name");
  });
  //获取售后人员列表
  getEmployee();
  // if (service.roles === "provider") {
  //   getEmployee(service.providerId);
  // } else if (baTable.form.operate === "edit") {
  //   setTimeout(() => {
  //     console.log("编辑表单", baTable.form.items);
  //     //编辑表单时拿到服务商id获取售后人员表
  //     getEmployee(baTable.form.items!.providerId);
  //   }, 1000);
  // }
});

//获取客户电话
const treeCustomer = (data: any, name: any, value: any) => {
  let arr: any[] = [];
  data.map((item: any) => {
    let obj: any = {};
    obj.name = item[name];
    obj.value = item[value];
    obj.id = item.id;
    obj.phone = item.phone;
    arr.push(obj);
  });
  return arr;
};

// watch(
//   () => baTable.form.items!.userType,
//   (newValue, oldValue) => {
//     if (newValue === "1") {
//       //区域用户获取区域数据
//       getRegionListByRole();
//       state.regionLoading = true;
//     } else if (newValue === "2") {
//       //企业用户获取企业数据
//       getCompanyList();
//     }
//   },
//   {
//     immediate: true, // 值如果是true会打开首次监听
//   }
// );
watch(filterText, (val) => {
  treeRef2.value!.filter(val);
});
defineExpose({
  getCheckeds,
});
</script>
<style lang="scss" scoped>
.el-scrollbar {
  overflow: auto;
  position: relative;
  height: 100%;

  .el-scrollbar__wrap {
    overflow: auto;
    height: 100%;
  }
}
.vertical-menus-scrollbar {
  height: v-bind(overviewMenusScrollbarHeight);
}
.tree-border {
  width: 100%;
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  // background: #fff none;
  border-radius: 4px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 98%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
</style>
